/**
 * \license
 * Copyright Lassi Marttala 2013
 * 
 * This file is part of dlt2jpa.
 *
 * dlt2jpa is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * dlt2jpa is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with dlt2jpa.  If not, see <http://www.gnu.org/licenses/>.
 */

package net.fizzl.dlt.message.parser;

import java.nio.ByteOrder;

import net.fizzl.dlt.ByteArrayUtils;
import net.fizzl.dlt.message.DltExtendedHeader;
import net.fizzl.dlt.message.DltMessage;
import net.fizzl.dlt.message.DltPayload;
import net.fizzl.dlt.message.DltStandardHeader;

public class DltMessageParser {

	public DltMessage fromByteArray(byte[] abuf) {
		DltMessage msg = new DltMessage();
		
		byte buf[] = new byte[abuf.length];
		System.arraycopy(abuf, 0, buf, 0, abuf.length);
		
		// Standard header
		DltStandardHeader sh = parseStandardHeader(buf);
		if(sh == null) return null;
		buf = ByteArrayUtils.removeHead(buf, sh.getLength());
		msg.setStadardHeader(sh);
		
		// Extended header
		DltExtendedHeader eh = null;
		if(sh.isUseExtendedHeader()) {
			eh = parseExtendedHeader(buf);
			if(eh == null) return null;
			buf = ByteArrayUtils.removeHead(buf, eh.getLength());
			msg.setExtendedHeader(eh);
		}
		
		ByteOrder bo = msg.getStadardHeader().isUseBigEndian() ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN;
		DltPayload payload = parsePayload(buf, msg.getExtendedHeader().getNumberOfArguments(), bo);
		if(payload == null) return null;
		buf = ByteArrayUtils.removeHead(buf, payload.getLength());
		msg.setPayload(payload);
		return msg;
	}

	private DltStandardHeader parseStandardHeader(byte[] buf) {
		DltStandardHeaderParser shParser = new DltStandardHeaderParser();
		DltStandardHeader sh = shParser.fromByteArray(buf);
		return sh;
	}
	
	private DltExtendedHeader parseExtendedHeader(byte[] buf) {
		DltExtendedHeaderParser ehParser = new DltExtendedHeaderParser();
		DltExtendedHeader eh = ehParser.fromByteArray(buf);
		return eh;
	}

	private DltPayload parsePayload(byte[] buf, int numberOfArguments, ByteOrder byteOrder) {
		DltPayloadParser plParser = new DltPayloadParser();
		DltPayload payload = plParser.fromByteArray(buf, numberOfArguments, byteOrder);
		return payload;
	}
}
